package com.hmall.order.listen;

import com.hmall.common.clients.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.Order;
import com.hmall.common.pojo.OrderDetail;
import com.hmall.order.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SpringRabbitDelayListener {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.ttl.queue", durable = "true"),
            exchange = @Exchange(name = "dl.ttl.direct"),
            key = "dl"
    ))
    public void listenDlQueue(String orderId) {
        log.info("订单已超时");
        //todo 1.根据orderId查询订单
        Order order = orderMapper.selectById(orderId);
        //todo 2.判断订单status是否为1
        if (order.getStatus() != 1) {
            return;
        }
        //todo 3.根据orderId查询订单详情，得到商品购买数量
        OrderDetail orderDetail = orderMapper.selectOrderDetailNumByOrderId(orderId);
        Integer num = orderDetail.getNum();
        //todo 4.根据orderId修改订单status为5（取消），注意幂等判断，避免重复消息
        HashOperations hashOperations = redisTemplate.opsForHash();
        Integer isOperation = (Integer) hashOperations.get("isOperation", orderId);
        if (isOperation == null || isOperation == 1) {
            order.setStatus(5);
            orderMapper.updateById(order);
            //todo 5.调用item-service，根据商品id、商品数量恢复库存
            Item item = itemClient.selectItem(orderDetail.getItemId());
            item.setStock(item.getStock() + num);
            itemClient.updateById(item);
            hashOperations.put("isOperation", orderId, 2);
        }
    }
}
